package org.jeecg.modules.system.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.entity.Zixishi;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class MenJinUtil {
    public static String genQrCode(Order order, Seat seat, Quyu quyu, Zixishi zixishi) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String qrCont = ""; //CB01  [999985,V123,20180225102513,20180226102513]
            String orderNum = order.getOrderNum();
            String startTime = sdf.format(order.getStartTime());
            String endTime = sdf.format(order.getEndTime());

            Set<String> devices = new HashSet<>();
            String devStr = "";
            devStr = StringUtils.isNotBlank(seat.getDevices())?devStr + "," + seat.getDevices():devStr;
            devStr = StringUtils.isNotBlank(quyu.getDevices())?devStr + "," + quyu.getDevices():devStr;
            devStr = StringUtils.isNotBlank(zixishi.getDevices())?devStr + "," + zixishi.getDevices():devStr;
            String[] dvs = StringUtils.split(devStr, ",");
            if (null != dvs && dvs.length > 0) {
                for (String dv : dvs) {
                    devices.add(dv);
                }
            }
            String devStrMenjin = StringUtils.join(devices, "|");
            qrCont = "[" + orderNum + "," + devStrMenjin + "," + startTime + "," + endTime + "]";
            System.out.println(qrCont);
            String enStr = "CB01" + RC4Util.encry_RC4_string(qrCont);
            File tmpFile = File.createTempFile("temp", ".png");
            QrConfig qrConfig = QrConfig.create();
            qrConfig.setBackColor(Color.WHITE);
            qrConfig.setForeColor(Color.BLACK);
            QrCodeUtil.generate(enStr, qrConfig, tmpFile);
            String url = MinioUtil.upload(new FileInputStream(tmpFile), "upload/qrcode/" + tmpFile.getName());
            tmpFile.delete();
            return url;
        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return "";
    }
}
